<?php
class BackupController 
	extends Zend_Controller_Action 
{
	
	public function indexAction()
	{
		try {

		    $db = Zend_Registry::get('db');
		    
            $config = Zend_Registry::get('configuration');
            
            $path = $config->backup->path;
            $date = date("Y-m-d-H-i-s");
            $params = $config->resources->db->params;
            $file = "{$path}/{$params->dbname}_" . $date . '.sql';
            $filed = "{$path}/{$params->dbname}_direcciones_" . $date . '.sql';
            $filez = "{$path}/{$params->dbname}_zonas_" . $date . '.sql';
            
            $command = sprintf("
                mysqldump -u %s --password=%s --databases %s -K --routines --skip-no-create-db --single-transaction --skip-no-data > %s",
                escapeshellcmd( $params->username ),
                escapeshellcmd( $params->password ),
                escapeshellcmd( $params->dbname ),
                escapeshellcmd($file)
            );
            exec($command);
		    
            //dump direcciones coords
            
            $sql = "
            SELECT idDireccion,	asText(punto)
            FROM {$params->dbname}.direcciones";
            
            $handle = fopen($filed, "w+");

            $stmt = $db->query( $sql );
            while ($row = $stmt->fetch()) {
              fwrite($handle, implode(",",$row) . ";\n");
            }

            fclose($handle);
            
            $sql = "
            SELECT idZona,	asText(coordenadas) 
            FROM {$params->dbname}.zonas";
            
             $handle = fopen($filez, "w+");

            $stmt = $db->query( $sql );
            while ($row = $stmt->fetch()) {
              fwrite($handle, implode(",",$row) . ";\n");
            }

            fclose($handle);
            
            //gzip compression
		    exec("gzip {$file}");
		    chmod("{$file}.gz", 0777);
		    
		    exec("gzip {$filed}");
		    chmod("{$filed}.gz", 0777);
		    
		    exec("gzip {$filez}");
		    chmod("{$filez}.gz", 0777);
		    
		    echo "Terminado";
		    
            
		} catch (Zend_Exception $e){
			$this->getHelper('Log')->exception( $e );
		}
		
	}
	
}